0% completed
Problem Statement
Given a binary tree and a number ‘S’, find all paths from root-to-leaf such that the sum of all the node values of each path equals ‘S’.
Constraints:
- The number of nodes in the tree is in the range
[0, 5000]. -1000 <= Node.val <= 1000-1000 <= targetSum <= 1000
Solution
This problem follows the Binary Tree Path Sum problem. We can follow the same DFS approach. There will be two differences though:
Every time we find a root-to-leaf path, we will store it in a list. We will traverse all paths and will not stop processing after finding the first path.
Here is the visual representation of the algorithm:
Code
Here is the code for this algorithm:
Time Complexity
The time complexity of the above algorithm is
We can calculate a tighter time complexity of
Space Complexity
If we ignore the space required for the allPaths list, the space complexity of the above algorithm will be O(N) in the worst case. This space will be used to store the recursion stack. The worst-case will happen when the given tree is a linked list (i.e., every node has only one child).
How can we estimate the space used for the allPaths array? Take the example of the following balanced tree:
Here we have seven nodes (i.e., N = 7). Since, for binary trees, there exists only one path to reach any leaf node, we can easily say that total root-to-leaf paths in a binary tree can’t be more than the number of leaves. As we know that there can’t be more than allPaths will be allPaths list will be
From the above discussion, we can conclude that our algorithm’s overall space complexity is
Also, from the above discussion, since for each leaf node, in the worst case, we have to copy log(N) nodes to store its path; therefore, the time complexity of our algorithm will also be
Similar Problems
Problem 1: Given a binary tree, return all root-to-leaf paths.
Solution: We can follow a similar approach. We just need to remove the “check for the path sum.”
Problem 2: Given a binary tree, find the root-to-leaf path with the maximum sum.
Solution: We need to find the path with the maximum sum. As we traverse all paths, we can keep track of the path with the maximum sum.
On this page
Problem Statement
Solution
Code
Time Complexity
Space Complexity
Similar Problems